module("png", package.seeall)

HEADER = string.char(137, 80, 78, 71, 13, 10, 26, 10)

local function getrawint(data, offset)
	local i1, i2, i3, i4 = string.byte(data, offset, offset + 3)
	return i1 * 16777216 + i2 * 65536 + i3 * 256 + i4
end

CHUNKHANDLERS = {
	IHDR = function (chunk)
		local data = chunk.data
		chunk.width = getrawint(data, 1)
		chunk.height = getrawint(data, 5)
	end,
}

local function getchunk(data, offset)
	local result = {}
	local length = getrawint(data, offset)
	result.type = data:sub(offset + 4, offset + 7)
	result.data = data:sub(offset + 8, offset + length + 7)
	result.crc = getrawint(data, offset + length + 8)
	local handler = CHUNKHANDLERS[result.type]
	if handler then handler(result) end
	return result, offset + length + 8
end

function getsize(file)
	local o = io.open(file, "rb")
	if not o then return 0, 0 end
	local data = o:read("*a")
	o:close()
	assert(data:sub(1, 8) == HEADER)
	local chunk = getchunk(data, 9)
	assert(chunk.type == "IHDR")
	return chunk.width, chunk.height
end
